<template>
  <div
    class="mesTechnologyOperate"
    v-loading="submitLoading"
    :element-loading-text="$i18n.t('mesTechnology.dataSubmitting')"
    element-loading-spinner="el-icon-loading"
  >
    <!-- 提交和返回按钮 -->
    <span class="operate">
      <el-button
        type="primary"
        :loading="btnLoading"
        @click="handleSubmit"
        :disabled="formDisabled"
      >
        {{ $i18n.t("common.submit") }}
      </el-button>
      <el-button @click="goBack">{{ $i18n.t("common.back") }}</el-button>
    </span>
    <el-tabs v-model="activeName" type="card" :before-leave="beforeLeave">
      <el-tab-pane
        :label="$i18n.t('mesTechnology.baseInfo')"
        name="baseInfo"
        v-loading="loading"
      >
        <ele-form
          v-model="baseInfoFormData"
          :disabled="formDisabled"
          v-bind="baseInfoFormConfig"
          ref="formData"
        >
        </ele-form>
      </el-tab-pane>
      <el-tab-pane
        :label="$i18n.t('mesTechnology.proOrder')"
        name="productSort"
      >
        <div class="version" v-if="query.type !== '1' && versionList.length">
          <el-radio-group v-model="currentVersion">
            <el-radio-button
              v-for="(item, index) in versionList"
              :key="index"
              :label="item.versionNumber"
            >
              {{ item.versionTitle }}
            </el-radio-button>
          </el-radio-group>
        </div>
        <div class="btm-pack">
          <div class="left-pack">
            <!-- 加工顺序顶部按钮 -->
            <div class="top">
              <div class="cross-shop">
                <div>
                  {{ $i18n.t("mesTechnology.isCrossShop") }}：{{
                    baseInfoFormData["crossShopFlag"] === "1"
                      ? $i18n.t("common.yes")
                      : $i18n.t("common.no")
                  }}
                </div>
                <div>
                  {{ $i18n.t("mesTechnology.processingWorkshop") }}：{{
                    workshopLists
                  }}
                </div>
              </div>
              <div class="tit">
                <h3>{{ $t("mesTechnology.processSingSequence") }}</h3>
                <div>
                  <!-- 添加工序按钮 -->
                  <el-button
                    @click="
                      $refs.workingDialog.init({
                        workshopCodes: currentWorkshopCode,
                      })
                    "
                    type="primary"
                    size="mini"
                    icon="el-icon-circle-plus-outline"
                    circle
                    :disabled="formDisabled"
                  ></el-button>
                  <!-- 删除工序按钮 -->
                  <el-button
                    @click="handleBatchDeleteProcess"
                    type="danger"
                    icon="el-icon-delete"
                    size="mini"
                    circle
                    :disabled="formDisabled"
                  ></el-button>
                </div>
              </div>
              <div class="radio">
                <el-radio-group
                  v-model="processingSequence.serialType"
                  :disabled="formDisabled"
                >
                  <el-radio :label="0">{{
                    $i18n.t("mesTechnology.sequentialProcessing")
                  }}</el-radio>
                  <el-radio :label="1">{{
                    $i18n.t("mesTechnology.parallelProcessing")
                  }}</el-radio>
                  <el-radio :label="2">{{
                    $i18n.t("mesTechnology.sequentialBatch")
                  }}</el-radio>
                  <el-radio :label="3">{{
                    $i18n.t("mesTechnology.parallelBatch")
                  }}</el-radio>
                </el-radio-group>
              </div>
            </div>
            <!-- 加工顺序列表 -->
            <div
              class="content"
              v-loading="dragLoading"
              :element-loading-text="$i18n.t('mesTechnology.loading')"
              element-loading-spinner="el-icon-loading"
            >
              <vue-draggable
                v-if="processingSequence.list.length > 0"
                v-model="processingSequence.list"
                :animation="300"
                :sort="true"
                handle=".handleDom"
                ghostClass="ghost"
                chosenClass="chosen"
                :forceFallback="true"
                :disabled="$route.query.type == 3"
              >
                <transition-group>
                  <div
                    class="groupitem"
                    v-for="(item, index) in processingSequence.list"
                    :key="item.processId"
                    @click="getProcessDetail(item['baseInfo'], index)"
                    :class="{ active: processId == item.processId }"
                  >
                    <!-- 新增或修改 -->
                    <el-checkbox
                      v-model="item.checked"
                      v-if="$route.query.type != 3"
                    ></el-checkbox>
                    <i
                      class="el-icon-s-grid handleDom"
                      @click.stop="() => {}"
                    ></i>
                    <p>
                      {{ getCardIndex(index) }}-{{
                        item["baseInfo"].processName
                      }}
                    </p>
                    <i
                      class="el-icon-delete delete"
                      @click.stop="handleDeleteWorking(item['baseInfo'])"
                      v-if="$route.query.type != 3"
                    ></i>
                  </div>
                </transition-group>
              </vue-draggable>
              <div v-else>
                <el-empty
                  :description="$t('mesTechnology.noProcess')"
                ></el-empty>
              </div>
            </div>
          </div>
          <!-- 工序信息详情的标签页 -->
          <div class="right-pack">
            <el-tabs v-model="activeProcess">
              <!-- 基本信息选项卡 -->
              <el-tab-pane
                :label="$i18n.t('mesTechnology.baseInfo')"
                name="processBase"
              >
                <ele-form
                  v-if="processId"
                  v-model="
                    processingSequence.list[selectedProcessIndex]['baseInfo']
                  "
                  v-bind="processBaseConfig"
                  :disabled="formDisabled"
                  class="base-info-form"
                >
                  <template v-slot:baseInfoTitle>
                    <h3>{{ $i18n.t("mesTechnology.baseInfo") }}</h3>
                  </template>
                  <template v-slot:baseInfo="{ formData }">
                    <el-row>
                      <el-col :span="6"
                        >{{ $i18n.t("mesTechnology.processCode") }}：{{
                          formData.processCode
                        }}</el-col
                      >
                      <el-col :span="6"
                        >{{ $i18n.t("mesTechnology.processName") }}：{{
                          formData.processName
                        }}</el-col
                      >
                      <el-col :span="6"
                        >{{ $i18n.t("mesTechnologyOperate.processTypeId") }}：{{
                          formData.processTypeName
                        }}</el-col
                      >
                      <el-col :span="6"
                        >{{ $i18n.t("mesTechnologyOperate.workshop2") }}：{{
                          formData.workshopName
                        }}</el-col
                      >
                      <el-col :span="24"
                        >{{
                          $i18n.t("mesTechnologyOperate.processContent")
                        }}：{{ formData.processContent }}</el-col
                      >
                      <el-col :span="24"
                        >{{ $i18n.t("common.remark") }}：{{
                          formData.remark
                        }}</el-col
                      >
                    </el-row>
                  </template>
                  <template v-slot:reportingManage>
                    <h3>{{ $i18n.t("mesTechnology.workInManaging") }}</h3>
                  </template>
                  <template v-slot:workingHoursManage>
                    <h3>
                      {{ $i18n.t("mesTechnology.workingHoursManagement") }}
                    </h3>
                  </template>
                </ele-form>
                <div v-else class="hint">
                  {{
                    $i18n.t(
                      "mesTechnology.pleaseAddAndSelectTheProcessingProcessOnTheLeft"
                    )
                  }}
                </div>
              </el-tab-pane>
              <!-- 生产用料选项卡 -->
              <el-tab-pane
                :label="$i18n.t('mesTechnology.production')"
                name="productionMaterial"
              >
                <div v-if="processId">
                  <el-button
                    type="primary"
                    :disabled="formDisabled"
                    @click="$refs.materialDialog.drawer = true"
                  >
                    {{ $i18n.t("mesTechnology.addMaterial") }}
                  </el-button>
                  <el-button
                    type="danger"
                    :disabled="formDisabled"
                    @click="
                      deleteTabTableData(
                        'productionMaterial',
                        $i18n.t('mesTechnologyOperate.goodsCode')
                      )
                    "
                    >{{ $i18n.t("common.delete") }}
                  </el-button>
                  <ele-table-editor
                    :tableOn="{
                      'selection-change': (data) => {
                        selectionChange(data, 'productionMaterial');
                      },
                    }"
                    ref="materialTableRef"
                    :isShowDelete="false"
                    style="margin-top: 10px; padding-right: 10px"
                    :isShowAdd="false"
                    :columns="materialColumn"
                    v-if="
                      processingSequence.list[selectedProcessIndex][
                        'productionMaterial'
                      ]
                    "
                    v-model="
                      processingSequence.list[selectedProcessIndex][
                        'productionMaterial'
                      ]
                    "
                  >
                    <template v-slot:operate="scope">
                      <el-button
                        @click="handleMaterial(scope)"
                        style="color: rgb(245, 108, 108)"
                        :disabled="query.type === '3' || scope.row.type !== '0'"
                        type="text"
                        >{{ $i18n.t("common.delete") }}
                      </el-button>
                    </template>
                  </ele-table-editor>
                </div>
                <div v-else class="hint">
                  {{
                    $i18n.t(
                      "mesTechnology.pleaseAddAndSelectTheProcessingProcessOnTheLeft"
                    )
                  }}
                </div>
              </el-tab-pane>
              <!-- 工艺动态属性选项卡 -->
              <el-tab-pane
                :label="$i18n.t('mesTechnologyCharacteristic.name')"
                name="dynamicAttribute"
              >
                <div v-if="processId">
                  <el-button
                    type="primary"
                    :disabled="formDisabled"
                    @click="$refs.attributeDialog.drawer = true"
                  >
                    {{ $i18n.t("mesTechnology.newDynamicAttribute") }}
                  </el-button>
                  <el-button
                    type="danger"
                    :disabled="formDisabled"
                    @click="
                      deleteTabTableData(
                        'dynamicAttribute',
                        $i18n.t('mesTechnology.dynamicAttribute')
                      )
                    "
                    >{{ $i18n.t("common.delete") }}
                  </el-button>
                  <ele-table-editor
                    :tableOn="{
                      'selection-change': (data) => {
                        selectionChange(data, 'dynamicAttribute');
                      },
                    }"
                    :isShowDelete="!formDisabled"
                    style="margin-top: 10px"
                    :isShowAdd="false"
                    :columns="attributeColumn"
                    v-model="
                      processingSequence.list[selectedProcessIndex][
                        'dynamicAttribute'
                      ]
                    "
                  >
                  </ele-table-editor>
                </div>
                <div v-else class="hint">
                  {{
                    $i18n.t(
                      "mesTechnology.pleaseAddAndSelectTheProcessingProcessOnTheLeft"
                    )
                  }}
                </div>
              </el-tab-pane>
              <!-- 工装治具选项卡 -->
              <el-tab-pane
                :label="$i18n.t('mesTechnology.sopFrockList')"
                name="fixture"
              >
                <div v-if="processId">
                  <el-button
                    type="primary"
                    :disabled="formDisabled"
                    @click="$refs.fixtureDialog.drawer = true"
                  >
                    {{ $i18n.t("mesTechnology.addWork") }}
                  </el-button>
                  <el-button
                    type="danger"
                    :disabled="formDisabled"
                    @click="
                      deleteTabTableData(
                        'fixture',
                        $i18n.t('mesTechnology.fixture')
                      )
                    "
                  >
                    {{ $i18n.t("common.delete") }}
                  </el-button>
                  <ele-table-editor
                    :tableOn="{
                      'selection-change': (data) => {
                        selectionChange(data, 'fixture');
                      },
                    }"
                    :isShowDelete="!formDisabled"
                    style="margin-top: 10px"
                    :isShowAdd="false"
                    :columns="fixtureColumn"
                    v-model="
                      processingSequence.list[selectedProcessIndex]['fixture']
                    "
                  >
                  </ele-table-editor>
                </div>
                <div v-else class="hint">
                  {{
                    $i18n.t(
                      "mesTechnology.pleaseAddAndSelectTheProcessingProcessOnTheLeft"
                    )
                  }}
                </div>
              </el-tab-pane>
              <!-- 设备选项卡 -->
              <el-tab-pane
                :label="$i18n.t('mesTechnology.equipment')"
                name="equipment"
              >
                <div v-if="processId">
                  <el-button
                    type="primary"
                    :disabled="formDisabled"
                    @click="$refs.equipmentDialog.drawer = true"
                  >
                    {{ $i18n.t("mesTechnology.addADevice") }}
                  </el-button>
                  <el-button
                    type="danger"
                    :disabled="formDisabled"
                    @click="
                      deleteTabTableData(
                        'equipment',
                        $i18n.t('mesTechnologyOperate.equipment')
                      )
                    "
                  >
                    {{ $i18n.t("common.delete") }}
                  </el-button>
                  <ele-table-editor
                    :tableOn="{
                      'selection-change': (data) => {
                        selectionChange(data, 'equipment');
                      },
                    }"
                    :isShowDelete="!formDisabled"
                    style="margin-top: 10px"
                    :isShowAdd="false"
                    :columns="equipmentColumn"
                    v-model="
                      processingSequence.list[selectedProcessIndex]['equipment']
                    "
                  >
                  </ele-table-editor>
                </div>
                <div v-else class="hint">
                  {{
                    $i18n.t(
                      "mesTechnology.pleaseAddAndSelectTheProcessingProcessOnTheLeft"
                    )
                  }}
                </div>
              </el-tab-pane>
            </el-tabs>
          </div>
        </div>
      </el-tab-pane>
    </el-tabs>
    <!-- 选择产品 -->
    <ProductDialog ref="productDialog" @response="resProductDialog" />
    <!-- 选择系列 -->
    <SeriesDialog ref="seriesDialog" @response="resSeriesDialog" />
    <!-- 选择加工工序 -->
    <WorkingDialog
      ref="workingDialog"
      :title="workingDialogTitle"
      :crossShopFlag="baseInfoFormData['crossShopFlag']"
      :selectedProcess="processingSequence.list"
      @selectedProcessList="resWorkingDialog"
    />
    <!-- 选择物料 -->
    <MaterialDialog ref="materialDialog" @response="resMaterialDialog" />
    <!-- 动态属性选择弹窗 -->
    <AttributeDialog ref="attributeDialog" @response="resAttributeDialog" />
    <!-- 工装选择弹窗 -->
    <FixtureDialog ref="fixtureDialog" @response="resFixtureDialog" />
    <!-- 设备选择弹窗 -->
    <EquipmentDialog ref="equipmentDialog" @response="resEquipmentDialog" />
    <!-- 正则表达式弹窗 -->
    <ele-dialog-table
      :title="$t('mesProcess.regularQuery')"
      width="800px"
      :visible.sync="regularDialogVisible"
      :formConfig="regularSearchConfig"
      :column="regularColumn"
      :getList="getRegularList"
      :hasFooter="true"
      :footer="regularDialogFooter"
      @customEvent="changeRegularDialog"
      @getSelectData="getSelectedRegular"
    >
    </ele-dialog-table>
  </div>
</template>

<script>
import { baseInfoMixin } from "./config";
import ProductDialog from "./components/ProductDialog.vue"; // 选择产品
import SeriesDialog from "./components/SeriesDialog.vue"; // 选择产品
import WorkingDialog from "./components/WorkingDialog.vue"; // 选择加工工序
import AttributeDialog from "./components/AttributeDialog.vue"; // 选择加工工序
import FixtureDialog from "./components/FixtureDialog.vue"; // 选择工装治具
import EquipmentDialog from "./components/EquipmentDialog.vue"; // 选择工装治具
import MaterialDialog from "./components/MaterialDialog.vue"; // 选择物料
import VueDraggable from "vuedraggable";
import { uniqueKey } from "@/utils/judge";
import { getDict } from "@/api/common";
import {
  addTechnology,
  updateTechnology,
  getProcessBaseInfo,
  getProcessSequenceList,
  getProcessMaterialList,
  getHistoryList,
  checkCodeExist,
} from "@/api/process/mesTechnologyOperate";
import EleTableEditor from "ele-table-editor";
import { regularDialog } from "./regularMixin";

export default {
  name: "Operate",
  mixins: [baseInfoMixin, regularDialog],
  components: {
    ProductDialog,
    SeriesDialog,
    VueDraggable,
    WorkingDialog,
    AttributeDialog,
    FixtureDialog,
    EquipmentDialog,
    MaterialDialog,
    EleTableEditor,
  },
  data() {
    const _this = this;
    return {
      query: {}, // 请求参数
      loading: false,
      columnRequired: false,
      dragLoading: false,
      submitLoading: false,
      activeName: "baseInfo",
      serialType: 3,
      baseInfoFormData: {}, // 表单基本信息
      processBaseConfig: {
        span: 24,
        labelPosition: "left",
        isShowSubmitBtn: false,
        isShowBackBtn: false,
        formDesc: {
          baseInfoTitle: {
            layout: 24,
          },
          baseInfo: {
            layout: 24,
          },
          reportingManage: {
            layout: 24,
          },
          isReportStart: {
            type: "switch",
            label: $i18n.t("mesTechnology.isReportStart2"),
            layout: 8,
            attrs: {
              "active-value": "1",
              "inactive-value": "0",
            },
          },
          reportOrNot: {
            type: "switch",
            label: $i18n.t("mesTechnology.reportOrNot"),
            layout: 8,
            attrs: {
              "active-value": "1",
              "inactive-value": "0",
            },
          },

          endReportModel: {
            type: "switch",
            label: $i18n.t("mesTechnology.endReportModel2"),
            layout: 8,
            attrs: {
              "active-value": "1",
              "inactive-value": "0",
              "active-text": $i18n.t("mesTechnology.auto"),
              "inactive-text": $i18n.t("mesTechnology.manual"),
            },
            vif: (data) => {
              return data["reportOrNot"] === "1";
            },
          },
          afterStep: {
            type: "switch",
            label: $i18n.t("mesTechnology.afterStep"),
            layout: 8,
            attrs: {
              "active-value": "1",
              "inactive-value": "0",
              // 'active-text': $i18n.t('mesTechnology.yes'),
              // 'inactive-text': $i18n.t('mesTechnology.no')
            },
            vif: (data) => {
              return data["reportOrNot"] === "1";
            },
          },
          workingHoursManage: {
            layout: 24,
          },
          standardTime: {
            type: "number",
            label: $i18n.t("mesTechnology.standardTime2"),
            layout: 12,
            attrs: {
              min: 0,
            },
            style: {
              width: "100px",
            },
            required: false,
          },
          prepareTime: {
            type: "number",
            label: $i18n.t("mesTechnology.prepareTime"),
            layout: 12,
            attrs: {
              min: 0,
            },
            required: false,
          },
        },
      },
      processingSequence: {
        // 表单生产顺序左侧的加工顺序
        serialType: 2, // 默认顺序加工
        list: [],
      },
      formData: {
        mesTechnology: {},
        param: {
          serialType: 2,
          list: [],
        },
        list: [],
      }, //基本信息数据
      processId: null, // 当前选中的工序ID
      btnLoading: false,
      activeProcess: "processBase",
      type: "",
      dict: {
        // 数组字典
        equipmentStatus: null, // 设备状态
        frockType: null, // 工装类型
        frockStatus: null, // 工装状态
        yesOrNo: null, // 是否
      },
      attributeKey: new Date().getTime(),
      selectedTableData: {}, // 存储选中的表格数据，删除时使用
      selectedRowIndex: null, // 当前选中的物料表格的行号
      currentVersion: null,
      versionList: [],
      attributeDialog: [],
      currentWorkshopCode: "", // 当前工序所属车间编码，如果有值，则只能选择该车间下的工序，否则可以选择所有车间下的工序
      workingDialogTitle: $i18n.t("mesTechnology.selectProcess"), // 用于工序弹窗标题显示
      workshopLists: "", // 选中工序的车间列表
    };
  },
  computed: {
    // 通过选中工序的processId，筛选出当前选中的工序的索引
    selectedProcessIndex() {
      const index = this.processingSequence.list.findIndex(
        (val) => val["baseInfo"].processId == this.processId
      );
      return index < 0 ? null : index;
    },
    getCardIndex() {
      return function (index) {
        const num = index + 1;
        return num < 10 ? `0${num}` : num;
      };
    },
    // 查看详情时，禁用表单
    formDisabled() {
      return this.query.type === "3"; // 1:添加 2:修改 3:详情 4:复制
    },
    attributeColumn() {
      return [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          align: "center",
          width: "80",
        },
        {
          prop: "propCode",
          label: $i18n.t("mesTechnology.propCode"),
          align: "center",
        },
        {
          prop: "propName",
          label: $i18n.t("mesTechnology.propName"),
          align: "center",
        },
        {
          prop: "characteristicCode",
          label: $i18n.t("mesTechnology.characteristicCode"),
          align: "center",
        },
        {
          prop: "characteristicName",
          label: $i18n.t("mesTechnology.characteristicName"),
          align: "center",
        },
        {
          prop: "isReport",
          label: $i18n.t("mesTechnology.isReport"),
          align: "center",
          width: "100px",
          content: {
            type: "el-switch",
            attrs: {
              "active-value": "1",
              "inactive-value": "0",
            },
          },
        },
      ];
    },
    fixtureColumn() {
      return [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          align: "center",
          width: "100px",
        },
        {
          prop: "frockTypeValue",
          label: $i18n.t("mesTechnology.frockTypeValue"),
          align: "center",
          options: this.dict["frockType"],
        },
        {
          prop: "frockCode",
          label: $i18n.t("mesTechnology.frockCode"),
          align: "center",
        },
        {
          prop: "frockName",
          label: $i18n.t("mesTechnology.frockName"),
          align: "center",
        },
        {
          prop: "startVerification",
          label: $i18n.t("mesTechnology.startVerification"),
          width: "100px",
          align: "center",
          options: this.dict["startVerification"],
        },
      ];
    },
    equipmentColumn() {
      return [
        {
          type: "selection",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          align: "center",
          width: "100px",
        },
        {
          prop: "equipmentCode",
          label: $i18n.t("mesTechnology.equipmentCode"),
          align: "center",
        },
        {
          prop: "equipmentName",
          label: $i18n.t("mesTechnology.equipmentName"),
          align: "center",
        },
        // {
        //   prop: 'equipmentStatus',
        //   label: '设备状态',
        //   align: 'center',
        //   options: this.dict['equipmentStatus']
        // }
      ];
    },
    materialColumn() {
      const _this = this;
      return [
        {
          type: "selection",
          align: "center",
        },
        {
          type: "index",
          label: $i18n.t("common.order"),
          align: "center",
          width: "80",
        },
        {
          prop: "materialCode",
          label: $i18n.t("mesTechnology.materialCode"),
          align: "center",
          width: "120",
        },
        {
          prop: "materialName",
          label: $i18n.t("mesTechnology.materialName"),
          align: "center",
          width: "160",
        },
        {
          prop: "materialSpecification",
          label: $i18n.t("mesTechnology.materialSpecification"),
          align: "center",
          width: "120",
        },
        {
          prop: "isKey",
          label: $i18n.t("mesTechnology.isKey"),
          align: "center",
          width: "120",
          content: {
            type: "el-select",
            options: [
              { text: $i18n.t("common.yes"), value: "1" },
              { text: $i18n.t("common.no"), value: "0" },
            ],
            attrs: ({ row }) => {
              return {
                disabled: _this.query.type === "3",
              };
            },
            change: (data, _, index) => {
              // 不是关键物料，不可编辑 是否重复和物料正则两列
              if (data === "0") {
                this.processingSequence.list[this.selectedProcessIndex][
                  "productionMaterial"
                ][index]["regularContent"] = "";
                this.processingSequence.list[this.selectedProcessIndex][
                  "productionMaterial"
                ][index]["regularName"] = "";
                this.processingSequence.list[this.selectedProcessIndex][
                  "productionMaterial"
                ][index]["regularCode"] = "";
                this.columnRequired = false;
              } else {
                this.columnRequired = true;
              }
              delete this.processingSequence.list[this.selectedProcessIndex][
                "productionMaterial"
              ][index]["isRepeat"];
            },
          },
        },
        {
          prop: "isRepeat",
          label: $i18n.t("mesTechnology.isRepeat"),
          labelClassName: this.columnRequired ? "req" : "input",
          align: "center",
          width: "120",
          content: {
            type: "el-select",
            attrs: ({ row }) => {
              return {
                disabled: row?.isKey === "0" || _this.query.type === "3",
              };
            },
            options: [
              { text: $i18n.t("common.yes"), value: "1" },
              { text: $i18n.t("common.no"), value: "0" },
            ],
          },
        },
        {
          prop: "regularContent",
          label: $i18n.t("mesTechnology.regularContent"),
          labelClassName: this.columnRequired ? "req" : "input",
          align: "center",
          width: "200",
          isShowSlot: true,
          content: {
            type: "search-bar",
            attrs: ({ row }) => {
              return {
                disabled: row.isKey === "0" || _this.query.type === "3",
              };
            },
            change: (data, _, index) => {
              _this.selectedRowIndex = index;
              _this.regularDialogVisible = true;
            },
          },
        },
        {
          prop: "remark",
          label: $i18n.t("common.remark"),
          width: "180",
          align: "center",
          content: {
            type: "el-input",
            attrs: ({ row }) => {
              return {
                disabled: row?.isKey === "0" || _this.query.type === "3",
                placeholder: $i18n.t("mesTechnologyOperate.enterRemarks"),
              };
            },
          },
        },
        {
          prop: "operate",
          label: $i18n.t("common.operation"),
          width: "120",
          align: "center",
          content: {
            type: "text",
            attrs: ({ row }) => {
              return {
                disabled: row?.type === "0" || _this.query.type === "3",
              };
            },
          },
        },
      ];
    },
  },
  created() {
    this.query = this.$route.query;
    if (this.query.id) {
      ["2", "3"].includes(this.query.type) && this.getProcessBaseInfo(); // 获取基本信息
      this.query.type === "4" &&
        (this.baseInfoFormData["crossShopFlag"] = this.query.crossShopFlag);
      this.getProcessSequenceList(); // 获取加工顺序列表信息
    }
    // 获取数据字典-设备状态
    getDict("equipment_status_method").then((res) => {
      this.dict["equipmentStatus"] = res.data.result.reduce((obj, item) => {
        obj[item.value] = item.description;
        return obj;
      }, {});
    });
    // 获取数据字典-工装类型
    getDict("frock_type").then((res) => {
      this.dict["frockType"] = res.data.result.reduce((obj, item) => {
        obj[item.value] = item.description;
        return obj;
      }, {});
    });
    // 获取数据字典-工装状态
    getDict("frock_status").then((res) => {
      this.dict["frockStatus"] = res.data.result.reduce((obj, item) => {
        obj[item.value] = item.description;
        return obj;
      }, {});
    });
    // 获取数据字典-开工验证
    getDict("frock_start_verification").then((res) => {
      this.dict["startVerification"] = res.data.result.reduce((obj, item) => {
        obj[item.value] = item.description;
        return obj;
      }, {});
    });
    getDict("yes_or_not").then((res) => {
      this.dict["yesOrNo"] = res.data.result.reduce((obj, item) => {
        obj[item.value] = item.description;
        return obj;
      }, {});
    });
    // 获取版本列表
    getHistoryList({ technologyCode: this.query.technologyCode }).then(
      (res) => {
        this.versionList = res.data.result || [];
        this.versionList.forEach((item) => {
          item["versionTitle"] = `${item["versionNumber"]}（${
            [
              $i18n.t("mesTechnologyOperate.wait"),
              $i18n.t("mesTechnologyOperate.Starting"),
              $i18n.t("mesTechnologyOperate.deactivated"),
            ][item["technologyStatus"]]
          }）`;
        });
      }
    );
  },
  mounted() {},
  methods: {
    // 点击生产顺序TAb时，判断必填项
    async beforeLeave(activeName, oldActiveName) {
      if (activeName != "productSort") return true;
      return await this.$refs.formData.validate();
    },
    // 修改和查看时，获取基本信息
    getProcessBaseInfo() {
      this.loading = true;
      this.processId = null;
      getProcessBaseInfo(this.query.id)
        .then((res) => {
          this.baseInfoFormData = res.data.result;
          this.currentVersion = res.data.result["versionNumber"];
        })
        .finally(() => {
          this.loading = false;
        });
    },
    // 修改和查看时，获取加工顺序列表信息
    getProcessSequenceList() {
      this.dragLoading = true;
      getProcessSequenceList(this.query.id).then((res) => {
        this.processingSequence.list = [];
        let workshopLists = [];
        res.data.result.forEach((item) => {
          if (!workshopLists.some((it) => it === item["workshopName"])) {
            workshopLists.push(item["workshopName"]);
          }
          this.processingSequence.list.push({
            checked: false,
            processId: item.processId,
            baseInfo: { ...item.mesProcess, processId: item.processId },
            productionMaterial: item.mesProcessMaterialList,
            dynamicAttribute: item.mesTechnologyCharacteristicList,
            fixture: item.mesTechnologyProcessFrockList,
            equipment: item.mesTechnologyProcessMachineList,
          });
        });
        this.workshopLists = workshopLists.join("，");
        this.processingSequence.serialType = res.data.result[0]?.serialType;
        this.dragLoading = false;
      });
    },
    // 选择产品后的回调
    resProductDialog(data) {
      this.$set(this.baseInfoFormData, "prodName", data[0].goodsName);
      this.$set(this.baseInfoFormData, "prodCode", data[0].goodsCode);
      // seriesName字段已有，如果此处设置成seriesName会导致不显示
      this.$set(this.baseInfoFormData, "seriesNameTmp", data[0].seriesName);
      this.$set(this.baseInfoFormData, "seriesCode", data[0].seriesCode);
      const params = { prodCode: data[0].goodsCode, technologyType: "product" };
      checkCodeExist(params).then((res) => {
        if (res.data.result) {
          this.$set(
            this.baseInfoFormData,
            "technologyCode",
            res.data.result.technologyCode
          );
          this.baseInfoFormConfig.formDesc.technologyCode.disabled = true;
        } else {
          this.$set(this.baseInfoFormData, "technologyCode", "");
          this.baseInfoFormConfig.formDesc.technologyCode.disabled = false;
        }
      });
    },
    // 选择系列后的回调
    resSeriesDialog(data) {
      this.$set(this.baseInfoFormData, "seriesName", data[0].seriesName);
      this.$set(this.baseInfoFormData, "seriesCode", data[0].seriesCode);
      const params = {
        seriesCode: data[0].seriesCode,
        technologyType: "series",
      };
      checkCodeExist(params).then((res) => {
        if (res.data.result) {
          this.$set(
            this.baseInfoFormData,
            "technologyCode",
            res.data.result.technologyCode
          );
        } else {
          this.$set(this.baseInfoFormData, "technologyCode", "");
        }
      });
    },
    // 在工序列表选择工序后回调
    resWorkingDialog(data) {
      this.baseInfoFormData["crossShopFlag"] = data.crossShopFlag;
      let workshopLists = [];
      const list = data["list"].map((item) => {
        if (!workshopLists.some((it) => it === item["workshopName"])) {
          workshopLists.push(item["workshopName"]);
        }
        let data = {
          ...item,
          code: item.processCode,
          name: item.processName,
          processId: item.id,
          reportOrNot: "1", // 是否报工
          isReportStart: item.isReportStart,
          endReportModel: item.endReportModel,
          afterStep: item.afterStep,
        };
        return {
          checked: false,
          processId: item.id,
          baseInfo: data, // 添加工序基本信息
          productionMaterial: null,
          dynamicAttribute: [],
          fixture: [],
          equipment: [],
        };
      });
      this.workshopLists = workshopLists.join("，");
      this.processingSequence.list = uniqueKey(list, "processId");
    },
    // 获取工序通用的生产用料配置
    async getProcessMaterialList(item) {
      let params = {
        technologyType: this.baseInfoFormData.technologyType,
        seriesCode: this.baseInfoFormData.seriesCode,
        processCode: item.processCode,
      };
      if (this.baseInfoFormData.technologyType === "product") {
        params["prodCode"] = this.baseInfoFormData.prodCode;
      }
      const res = await getProcessMaterialList(params);
      return res.data.result || [];
    },
    // 在选择物料后回调
    resMaterialDialog(data) {
      let result = [];
      data.forEach((item) => {
        result.push({
          type: "0",
          id: item.id,
          materialCode: item.goodsCode,
          materialName: item.goodsName,
          materialSpecification: item.specification,
          isKey: "0", // 是否关键物料，默认否
        });
      });
      this.processingSequence.list[this.selectedProcessIndex][
        "productionMaterial"
      ] = uniqueKey(
        [
          ...this.processingSequence.list[this.selectedProcessIndex][
            "productionMaterial"
          ],
          ...result,
        ],
        "materialCode"
      );
    },
    // 在动态属性列表中选择属性后回调
    resAttributeDialog(data) {
      const uniqueObj = (arr, keyArr) => {
        const map = new Map();
        return arr.filter((item) => {
          const key = keyArr.map((i) => item[i]).join("-");
          return !map.has(key) && map.set(key, 1);
        });
      };
      this.attributeDialog.push(...JSON.parse(JSON.stringify(data)));
      this.processingSequence.list[this.selectedProcessIndex][
        "dynamicAttribute"
      ] = uniqueObj(
        [
          ...this.processingSequence.list[this.selectedProcessIndex][
            "dynamicAttribute"
          ],
          ...data,
        ],
        ["propCode", "characteristicCode"]
      );
    },
    // 在工装列表中选择工装后回调
    resFixtureDialog(data) {
      this.processingSequence.list[this.selectedProcessIndex]["fixture"] =
        uniqueKey(
          [
            ...this.processingSequence.list[this.selectedProcessIndex][
              "fixture"
            ],
            ...data,
          ],
          "frockCode"
        );
    },
    // 在设备列表中选择设备后回调
    resEquipmentDialog(data) {
      data.forEach((item) => {
        item["id"] = item.equipmentCode;
      });
      this.processingSequence.list[this.selectedProcessIndex]["equipment"] =
        uniqueKey(
          [
            ...this.processingSequence.list[this.selectedProcessIndex][
              "equipment"
            ],
            ...data,
          ],
          "equipmentCode"
        );
    },
    // 删除加工顺序
    handleDeleteWorking(val) {
      this.$confirm(
        $i18n.t("common.deleteSingle", {
          name: $i18n.t("mesTechnology.nameProcess"),
        }),
        $i18n.t("common.tip"),
        {
          confirmButtonText: $i18n.t("common.ok"),
          cancelButtonText: $i18n.t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        let index = this.processingSequence.list.findIndex(
          (item) => item.processId == val.processId
        );
        this.processingSequence.list.splice(index, 1);
        // 判断删除的是否是当前选择的工序
        if (this.processId == val.processId) {
          this.processId = null;
        }
      });
    },
    // 批量删除工序
    handleBatchDeleteProcess() {
      const isPass = this.processingSequence.list.some((val) => val.checked);
      if (!isPass) return;
      this.$confirm(
        $i18n.t("mesTechnologyOperate.confirmDeleteSelectedProcess"),
        $i18n.t("common.tip"),
        {
          confirmButtonText: $i18n.t("common.ok"),
          cancelButtonText: $i18n.t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        this.processId = null;
        this.processingSequence.list = this.processingSequence.list.filter(
          (val) => !val.checked
        );
      });
    },
    // 删除选项卡中列表的数据
    deleteTabTableData(tab, title) {
      if (
        !this.selectedTableData[tab] ||
        this.selectedTableData[tab].length === 0
      ) {
        this.$message.error($i18n.t("mesTechnology.pleaseSelectOneOrMoreData"));
        return;
      }
      this.$confirm(
        $i18n.t("mesTechnology.deleteConfirm2", { title: title }),
        $i18n.t("common.tip"),
        {
          confirmButtonText: $i18n.t("common.ok"),
          cancelButtonText: $i18n.t("common.cancel"),
          type: "warning",
        }
      ).then(() => {
        this.processingSequence.list[this.selectedProcessIndex][tab] =
          this.processingSequence.list[this.selectedProcessIndex][tab].filter(
            (item) => {
              return !this.selectedTableData[tab].some((i) => i.id === item.id);
            }
          );
      });
    },
    // 选中工序后，获取工序详情
    getProcessDetail(data, index) {
      this.selectedTableData = {};
      if (!this.processingSequence.list[index]["productionMaterial"]) {
        let params = {
          technologyType: this.baseInfoFormData.technologyType,
          seriesCode: this.baseInfoFormData.seriesCode,
          processCode: data.processCode,
        };
        if (this.baseInfoFormData.technologyType === "product") {
          params["prodCode"] = this.baseInfoFormData.prodCode;
        }
        getProcessMaterialList(params).then((res) => {
          this.processingSequence.list[index]["productionMaterial"] =
            res.data.result || [];
        });
      }
      this.processId = data.processId;
    },
    // 表单提交
    handleSubmit() {
      // 校验基本信息是否填写完整
      this.$refs.formData
        .validate()
        .then((res) => {
          // 校验加工顺序是否存在
          if (
            this.processingSequence.list &&
            Array.isArray(this.processingSequence.list) &&
            this.processingSequence.list.length == 0
          ) {
            this.$message.error(
              $i18n.t("mesTechnology.pleaseAddProcessingSequence")
            );
            this.activeName = "productSort";
            return;
          }
          // 是否验证通过
          let isPass = true;
          if (
            Array.isArray(this.processingSequence.list) &&
            this.processingSequence.list.length > 0
          ) {
            this.processingSequence.list.forEach((item) => {
              if (
                item["productionMaterial"] &&
                Array.from(item["productionMaterial"]) &&
                item["productionMaterial"].length > 0
              ) {
                item["productionMaterial"].forEach((material, index) => {
                  if (material["isKey"] === "1") {
                    if (!!!material["isRepeat"]) {
                      setTimeout(() => {
                        this.$message.error(
                          $i18n.t("mesTechnology.errorHint1", {
                            name: item["baseInfo"]["processName"],
                            index: index + 1,
                          })
                        );
                      }, 50);
                      this.activeName = "productSort";
                      isPass = false;
                    }
                    if (!material["regularCode"]) {
                      setTimeout(() => {
                        this.$message.error(
                          $i18n.t("mesTechnology.errorHint2", {
                            name: item["baseInfo"]["processName"],
                            index: index + 1,
                          })
                        );
                      }, 50);
                      this.activeName = "productSort";
                      isPass = false;
                    }
                  }
                });
              }
            });
          }
          // 1:新增 2:修改 3:查看 4:复制
          // 修改和复制为同一个接口
          if (isPass) {
            this.baseInfoFormData.id && this.query.type === "2"
              ? this.handleUpdate()
              : this.handleAdd();
          }
        })
        .catch((err) => {
          console.log("失败", err);
          this.btnLoading = false;
          this.activeName = "baseInfo";
          this.$message.error(
            $i18n.t(
              "mesTechnology.pleaseFillInTheNecessaryItemsInTheBasicInformation"
            )
          );
        });
    },
    // 处理数据，再提交（更新或者新增）
    transformData() {
      // 如果不是默认工艺，将车间数据删除
      this.baseInfoFormData.isDefaultTechnology === "0" &&
        delete this.baseInfoFormData.workshopName;
      // 将seriesNameTmp转换成seriesName
      if (this.baseInfoFormData["technologyType"] === "product") {
        this.baseInfoFormData["seriesName"] =
          this.baseInfoFormData["seriesNameTmp"];
      }
      // 工艺复制，去掉id，取crossShopFlag
      if (this.query.type === "4") {
        delete this.baseInfoFormData.id;
      }
      let param = {
        serialType: this.processingSequence["serialType"],
        list: [],
      };
      let list = [];
      this.processingSequence["list"].forEach((item, index) => {
        param.list.push({
          processId: item.processId,
          serialNumber: index + 1,
        });
        // 去掉设备列表中的ID
        item["equipment"].length &&
          item["equipment"].forEach((equipment) => {
            delete equipment["id"];
          });
        list.push({
          mesTechProcessDetail: item.baseInfo,
          mesProcessMaterialList: item.productionMaterial,
          mesTechnologyCharacteristicList: item.dynamicAttribute,
          mesTechnologyProcessFrockList: item.fixture,
          mesTechnologyProcessMachineList: item.equipment,
        });
      });
      return {
        mesTechnology: this.baseInfoFormData,
        param,
        list,
      };
    },
    // 修改提交
    handleUpdate() {
      const data = this.transformData();
      this.btnLoading = true;
      this.submitLoading = true;
      updateTechnology(data)
        .then((res) => {
          this.$message.success($i18n.t("common.editSuccess"));
          this.goBack();
        })
        .finally(() => {
          this.btnLoading = false;
          this.submitLoading = false;
        });
    },
    // 新增提交
    handleAdd() {
      const data = this.transformData();
      this.btnLoading = true;
      this.submitLoading = true;
      addTechnology(data)
        .then((res) => {
          let title =
            this.query.type == 4
              ? $i18n.t("common.copyMsg")
              : $i18n.t("common.addSuccess");
          this.$message.success(title);
          this.goBack();
        })
        .finally(() => {
          this.btnLoading = false;
          this.submitLoading = false;
        });
    },
    goBack() {
      // 关闭当前选项卡，qiankun模式下和独立运行两种情况
      if (this.isMicro) {
        this.closeTab({
          pathname: window.location.pathname,
        });
      } else {
        this.$store.commit(
          "SET_TOPMENUS",
          this.$store.getters.topmenus.filter(
            (item) => item.pathname != window.location.pathname
          )
        );
      }
      this.$router.push("/process/mesTechnology");
    },
    // 生产物料、工装治具等表格选中的数据，用于批量删除
    selectionChange(data, tab) {
      this.selectedTableData[tab] = data;
    },
    // 生产物料的单条数据删除
    handleMaterial(data) {
      this.processingSequence.list[this.selectedProcessIndex][
        "productionMaterial"
      ].splice(data.$index, 1);
    },
  },
  watch: {
    currentVersion(newVal, oldVal) {
      if (oldVal) {
        this.query.id = this.versionList.find(
          (item) => item.versionNumber === newVal
        )?.id;
        this.getProcessBaseInfo();
        this.getProcessSequenceList();
      }
    },
    "processingSequence.list": {
      handler(val) {
        if (val.length === 0) {
          this.currentWorkshopCode = "";
        } else {
          const workshopArr = val.map(
            (item) => item["baseInfo"]["workshopCode"]
          );
          this.currentWorkshopCode = workshopArr.join(",");
        }
      },
    },
  },
};
</script>

<style lang="scss" scoped>
@import "./index.scss";

.right-pack {
  h3 {
    font-size: 14px;
    height: 16px;
    line-height: 16px;
    margin: 0 0 6px 0;
    font-weight: bolder;
  }

  h3::before {
    content: "";
    display: inline-block;
    background-color: #0f9e5e;
    width: 6px;
    height: 14px;
    line-height: 14px;
    margin: 0px 6px -2px 0px;
    border-radius: 2px;
  }

  /deep/ .ele-form .el-form-item__content {
    margin-left: 10px !important;
  }

  // tab选项卡中的提示信息
  // 请在左侧添加并选择加工工序
  .hint {
    font-size: 13px;
    text-align: center;
    color: #3c7fcd;
  }
}
/deep/.el-table__cell {
  .req::before {
    content: "*" !important;
    color: red;
  }
}
</style>
